package com.ruoyi.web.controller.common;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.stream.JsonReader;
import com.ruoyi.common.response.Result;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/region")
public class RegionController {
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("listProvince")
    public Result listProvince() {
        Object o = redisTemplate.opsForHash().get("region", "province");
        JSONArray provinceArr = (JSONArray) o;
        List<JSONObject> provinceList = new ArrayList<>();
        for (Object object : provinceArr) {
            JSONObject provinceJson = (JSONObject) object;
            provinceList.add(provinceJson);
        }
        for (JSONObject jsonObject : provinceList) {
            jsonObject.remove("@type");
        }
        return Result.success(provinceList);
    }

    @GetMapping("listCitiesByProvinceCode")
    public Result listCitiesByProvinceCode(String provinceCode) {
        //先从redis里取，没有的话，则从json文件里查询
        Object o = redisTemplate.opsForHash().get("region", "city");
        JSONArray cityArr = (JSONArray) o;
        List<JSONObject> cityList = new ArrayList<>();
        for (Object object : cityArr) {
            JSONObject cityJson = (JSONObject) object;
            cityList.add(cityJson);
        }
        List<JSONObject> result = new ArrayList<>();
        if (StringUtils.isEmpty(provinceCode)) {
            for (JSONObject item : cityList) {
                result.addAll(item.getList("children", JSONObject.class));
            }
        } else {
            for (JSONObject item : cityList) {
                if (provinceCode.equals(item.getString("code"))) {
                    result = item.getList("children", JSONObject.class);
                }
            }
        }
        for (JSONObject jsonObject : result) {
            jsonObject.remove("@type");
        }
        return Result.success(result);
    }

    @GetMapping("listAreasByCityCode")
    public Result listAreasByCityCode(String cityCode) {
        //先从redis里取，没有的话，则从json文件里查询
        Object o = redisTemplate.opsForHash().get("region", "area");
        JSONArray areaArr = (JSONArray) o;
        List<JSONObject> areaList = new ArrayList<>();
        for (Object object : areaArr) {
            JSONObject areaJson = (JSONObject) object;
            areaList.add(areaJson);
        }
        List<JSONObject> result = new ArrayList<>();
        if (StringUtils.isEmpty(cityCode)) {
            for (JSONObject item : areaList) {
                result.addAll(item.getList("children", JSONObject.class));
            }
        } else {
            for (JSONObject item : areaList) {
                if (cityCode.equals(item.getString("code"))) {
                    result = item.getList("children", JSONObject.class);
                }
            }
        }
        for (JSONObject jsonObject : result) {
            jsonObject.remove("@type");
        }
        return Result.success(result);
    }

    @GetMapping("listRegion")
    public Result listRegion() {
        JSONObject returnJSON = new JSONObject();
        Object provinceObj = redisTemplate.opsForHash().get("region", "province");
        Object cityObj = redisTemplate.opsForHash().get("region", "city");
        Object areaObj = redisTemplate.opsForHash().get("region", "area");
        JSONArray provinceArr = (JSONArray) provinceObj;
        JSONArray cityArr = (JSONArray) cityObj;
        JSONArray areaArr = (JSONArray) areaObj;
        List<JSONObject> provinceList = new ArrayList<>();
        List<JSONObject> cityList = new ArrayList<>();
        List<JSONObject> areaList = new ArrayList<>();
        for (Object object : provinceArr) {
            JSONObject provinceJson = (JSONObject) object;
            provinceJson.remove("@type");
            provinceList.add(provinceJson);
        }
        for (Object object : cityArr) {
            JSONObject jsonObject = (JSONObject) object;
            List<JSONObject> cityJsonList = jsonObject.getList("children", JSONObject.class);
            cityList.addAll(cityJsonList);
        }
        for (JSONObject cityJson : cityList) {
            cityJson.remove("@type");
        }
        for (Object object : areaArr) {
            JSONObject jsonObject = (JSONObject) object;
            List<JSONObject> areaJsonList = jsonObject.getList("children", JSONObject.class);
            areaList.addAll(areaJsonList);
        }
        for (JSONObject areaJson : areaList) {
            areaJson.remove("@type");
        }
        returnJSON.put("province", provinceList);
        returnJSON.put("city", cityList);
        returnJSON.put("area", areaList);
        return Result.success(returnJSON);
    }

    public static JSONArray readJsonArrayFromResource(String resourceName) throws JSONException, IOException {
        // 1. 读取文件
        InputStream inputStream = JsonReader.class.getClassLoader().getResourceAsStream(resourceName);

        // 2. 解析JSON
        ObjectMapper objectMapper = new ObjectMapper();

        JsonNode jsonNode = objectMapper.readTree(inputStream);
        if (jsonNode.isArray()) {
            JSONArray jsonArray = JSONArray.parseArray(jsonNode.toString());
            return jsonArray;
        } else {
            return null;
        }
    }

    /**
     * 从redis中获取省市区联动组件所需数据
     * @return
     */
    @GetMapping("getRedisRegionList")
    public Result getRedisRegionList() {
        String obj = (String) redisTemplate.opsForValue().get("regionList");
        JSONArray result = JSONArray.parseArray(obj);
        return Result.success(result);
    }
}
